package de.pernpas.stadtfuehrer.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import de.pernpas.stadtfuehrer.entity.EMF;
import de.pernpas.stadtfuehrer.entity.User;

public class UserServiceImpl implements UserService {
	
	private static final String PASSWORD = "password";
	private static final String PSEUDONYM = "pseudonym";
	
	public UserServiceImpl() {
		super();
	}


	@Override
	public void create(User user) {
		EntityManager em = EMF.get().createEntityManager();
		em.persist(user);
		em.close();
	}

	@Override
	public User retrieve() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void update(User user) {
		EntityManager em = EMF.get().createEntityManager();
		em.merge(user);
		em.close();
	}

	@Override
	public boolean delete(User user) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> retrieveAllUser() {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em.createNamedQuery("allUser");
		List <User> result = query.getResultList();
		// becouse of BUg http://code.google.com/p/datanucleus-appengine/issues/detail?id=24 I have to call size()
		result.size();
		em.close();
		return new ArrayList<User>(result);
	}


	@Override
	public User getUser(String pseudonym, String password) {
		EntityManager em = EMF.get().createEntityManager();
		Query query = em.createQuery("Select u from " + User.class.getSimpleName() + 
				" u where u.pseudonym = :" + PSEUDONYM + " and u.password = :" + PASSWORD);
		query.setParameter(PSEUDONYM, pseudonym);
		query.setParameter(PASSWORD, password);
		User result = (User) query.getSingleResult();
		em.close();
		return result;
	}

}
